package com.maiji.cloud.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.maiji.cloud.entities.shopingmall.ShareOrderRule;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.alibaba.fastjson.JSON;
import com.maiji.cloud.entities.login.AppUser;
import com.maiji.cloud.entities.login.ReduceWeightFundLogEntity;
import com.maiji.cloud.entities.login.ShareWeightHelpRule;
import com.maiji.cloud.entities.login.ShareWeightHelpUserLogEntity;
import com.maiji.cloud.entities.login.ShareWeightRuleEntity;
import com.maiji.cloud.entities.login.UserInfo;
import com.maiji.cloud.entities.login.WeightChangeLog;
import com.maiji.cloud.mapper.ReduceWeightFundLogMapper;
import com.maiji.cloud.mapper.ShareWeightHelpUserLogMapper;
import com.maiji.cloud.mapper.UserInfoMapper;
import com.maiji.cloud.mapper.WeightChangeLogMapper;
import com.maiji.cloud.request.BaseDataReqDto;
import com.maiji.cloud.request.login.ReduceWeightFundLogReqData;
import com.maiji.cloud.response.BaseDataResDto;
import com.maiji.cloud.response.BaseResDto;
import com.maiji.cloud.response.Status;
import com.maiji.cloud.response.login.ActivityShareRuleConfigResData;
import com.maiji.cloud.response.login.ReduceWeightFundLogResData;
import com.maiji.cloud.response.login.ShareWeightDetailsData;
import com.maiji.cloud.response.login.ShareWeightUserHelpList;
import com.maiji.cloud.service.ActivityShareRuleConfigService;
import com.maiji.cloud.service.AppUserService;
import com.maiji.cloud.service.ShareWeightService;
import com.maiji.cloud.utils.Arith;
import com.maiji.cloud.utils.CommonIntValueEnum;
import com.maiji.cloud.utils.TimeUtil;
import com.maiji.cloud.utils.UUID_MD5;

@Service
@Transactional
public class ShareWeightServiceImpl implements ShareWeightService {

	private static final Logger logger = LoggerFactory.getLogger(ShareWeightServiceImpl.class);
	@Autowired
	private MongoTemplate mongoTemplate;
	@Autowired
	private ShareWeightHelpUserLogMapper shareWeightHelpUserLogMapper;
	@Autowired
	private ReduceWeightFundLogMapper reduceWeightFundLogMapper;
	@Autowired
	private AppUserService appUserService;
	@Autowired
	private UserInfoMapper userInfoMapper;
	@Autowired
	private WeightChangeLogMapper weightChangeLogMapper;
	@Autowired
    private ActivityShareRuleConfigService activityShareRuleConfigService;
	
	@Override
	public BaseResDto addShareWeightRuleInfo(BaseDataReqDto<ShareWeightRuleEntity> param) {

		ShareWeightRuleEntity shareWeightRuleEntity = param.getData();
		shareWeightRuleEntity.setUu_id(UUID_MD5.getUUID());
		mongoTemplate.save(shareWeightRuleEntity, ShareWeightRuleEntity.TABLE_NAME);
		
		return new BaseResDto(Status.SUCCESS);
	}

	@Override
	public ShareWeightRuleEntity getShareWeightRuleEntityInfo() {
		ShareWeightRuleEntity shareWeightRuleEntity = mongoTemplate.findOne(
				new Query(Criteria.where("type").is(CommonIntValueEnum.MONGO_RULE_TYPE_REDUCE_WEIGHT_BASE_FUND.getValue())),
				ShareWeightRuleEntity.class, ShareWeightRuleEntity.TABLE_NAME);
		return shareWeightRuleEntity;
	}

	@Override
	public BaseDataResDto<Boolean> shareWeightUserHelp(BaseDataReqDto<String> param, String maijiToken) {
		logger.info("ShareWeightServiceImpl.shareWeightUserHelp,param is {},maijiToken", JSON.toJSON(param),
				maijiToken);
		// 获得用户id
		AppUser appUser = appUserService.checkToken(maijiToken);

		if (appUser == null) {
			logger.info("ShareWeightServiceImpl.shareWeightUserHelp,appUser is {}", JSON.toJSONString(appUser));
			return new BaseDataResDto<Boolean>(Status.PARAMETERERROR, "token 无效 ");
		}
		String reduceWeightFundLogId = param.getData();
		ReduceWeightFundLogEntity reduceWeightFundLogEntity = reduceWeightFundLogMapper
				.selectById(reduceWeightFundLogId);
		
		if(reduceWeightFundLogEntity.getUserId().equals(appUser.getUuId())) {
			return new BaseDataResDto<Boolean>(Status.PARAMETERERROR, "无法为自己点赞助力 ");
		}

		if (reduceWeightFundLogEntity.getEndTime().getTime() < System.currentTimeMillis()) {
			return new BaseDataResDto<Boolean>(Status.PARAMETERERROR, "助力失败 ");
		}

		// 本次分享的体重该用户是否已经助力
		ShareWeightHelpUserLogEntity shareWeightHelpUserLog = shareWeightHelpUserLogMapper
				.selectOneByreduceWeightFundLogId(reduceWeightFundLogId, appUser.getUuId());
		if (shareWeightHelpUserLog != null) {
			return new BaseDataResDto<Boolean>(Status.PARAMETERERROR, "已经帮该用户助力过一次 ");
		}

		// 今天是否帮别人助力过
		shareWeightHelpUserLog = shareWeightHelpUserLogMapper.selectOneByTime(TimeUtil.getZeroTime(new Date()),
				appUser.getUuId());

		ShareWeightHelpRule shareWeightHelpRule = mongoTemplate.findOne(
				new Query(Criteria.where("type")
						.is(CommonIntValueEnum.MONGO_RULE_TYPE_REDUCE_WEIGHT_HELP_FUND.getValue())),
				ShareWeightHelpRule.class, ShareWeightRuleEntity.TABLE_NAME);

		if (shareWeightHelpUserLog != null && shareWeightHelpRule.getIsNo() == 0) {
			return new BaseDataResDto<Boolean>(Status.PARAMETERERROR, "今天已经帮别人助力过 ");
		}

		// 判断是否是新人
		ShareWeightHelpUserLogEntity shareWeightHelpUserLogEntity = shareWeightHelpUserLogMapper
				.selectOneByUserId(appUser.getUuId());

		Double helpMoney = null;
		Integer isNewUser = 0;
		if (shareWeightHelpUserLogEntity != null) {
			helpMoney = Arith.getRandomNum(shareWeightHelpRule.getOldUserMinMoney(),
					shareWeightHelpRule.getOldUserMaxMoney());
		} else {
			helpMoney = Arith.getRandomNum(shareWeightHelpRule.getNewUserMinMoney(),
					shareWeightHelpRule.getNewUserMaxMoney());
			isNewUser = 1;
		}

		UserInfo userInfo = userInfoMapper.selectOneByUserId(appUser.getUuId());

		shareWeightHelpUserLogEntity = new ShareWeightHelpUserLogEntity();

		shareWeightHelpUserLogEntity.setUuId(UUID_MD5.getUUID());
		shareWeightHelpUserLogEntity.setHeadUrl(userInfo.getHeadUrl());
		shareWeightHelpUserLogEntity.setNickname(userInfo.getNickName());
		shareWeightHelpUserLogEntity.setUserId(appUser.getUuId());
		shareWeightHelpUserLogEntity.setReduceWeightFundLogId(reduceWeightFundLogId);
		shareWeightHelpUserLogEntity.setWeightChangeLogId(reduceWeightFundLogEntity.getWeightChangeLogId());
		shareWeightHelpUserLogEntity.setHelpMoney(helpMoney);
		shareWeightHelpUserLogEntity.setInTime(new Date());
		shareWeightHelpUserLogEntity.setIsNewUser(isNewUser);

		shareWeightHelpUserLogMapper.insert(shareWeightHelpUserLogEntity);

		return new BaseDataResDto<Boolean>(Status.SUCCESS);
	}

	@Override
	public BaseDataResDto<ShareWeightDetailsData> getShareWeightDetails(BaseDataReqDto<String> param,String maijiToken) {
		logger.info("UserServiceImpl.getKetonuria ,param is {}", JSON.toJSONString(param));
		// 获得用户id
		AppUser appUser = null;
		if(StringUtils.isNotBlank(maijiToken)) {
			appUser = appUserService.checkToken(maijiToken);

			if (appUser == null) {
				logger.info("UserServiceImpl.getShareWeightDetails,appUser is {}", JSON.toJSONString(appUser));
				return new BaseDataResDto<ShareWeightDetailsData>(Status.PARAMETERERROR, "token 无效 ");
			}
		}
		

		ReduceWeightFundLogEntity reduceWeightFundLogEntity = reduceWeightFundLogMapper.selectById(param.getData());
		if(reduceWeightFundLogEntity == null) return new BaseDataResDto<ShareWeightDetailsData>(Status.ERROR,"体重分享记录id错误");

		BaseDataResDto<ShareWeightDetailsData> baseDataResDto = new BaseDataResDto<ShareWeightDetailsData>(
				Status.SUCCESS);
		
		if (reduceWeightFundLogEntity.getWeightChangeLogId() != null) {
			WeightChangeLog weightChangeLog = weightChangeLogMapper
					.selectById(reduceWeightFundLogEntity.getWeightChangeLogId());
			
			

			UserInfo userInfo = userInfoMapper.selectOneByUserId(weightChangeLog.getUserId());

			ShareWeightHelpRule shareWeightHelpRule = mongoTemplate.findOne(
					new Query(Criteria.where("type")
							.is(CommonIntValueEnum.MONGO_RULE_TYPE_REDUCE_WEIGHT_HELP_FUND.getValue())),
					ShareWeightHelpRule.class, ShareWeightRuleEntity.TABLE_NAME);

			ShareWeightDetailsData shareWeightDetailsData = new ShareWeightDetailsData();
			shareWeightDetailsData.setLoseWeight(reduceWeightFundLogEntity.getLoseWeight());
			shareWeightDetailsData.setIsBaseFund(reduceWeightFundLogEntity.getIsBaseFund());
			shareWeightDetailsData.setBaseFund(reduceWeightFundLogEntity.getMoney());
			shareWeightDetailsData.setHeadUrl(userInfo.getHeadUrl());
			shareWeightDetailsData.setNickname(userInfo.getNickName());
			shareWeightDetailsData.setReduceWeightFundLogId(reduceWeightFundLogEntity.getUuId());
			shareWeightDetailsData.setNewUserMaxMoney(shareWeightHelpRule.getNewUserMaxMoney());
			shareWeightDetailsData.setEndTime(reduceWeightFundLogEntity.getEndTime());
			shareWeightDetailsData.setHelpmMoney(shareWeightHelpUserLogMapper.getSumFund(param.getData()));
			
			BaseDataResDto<ActivityShareRuleConfigResData> reponseData =  activityShareRuleConfigService.getActivityShareRuleConfigByType(CommonIntValueEnum.ACTIVITY_SHARE_RULE_CONFIG_TYPE_REDUCE_WEIGHT.getValue());
			shareWeightDetailsData.setParam(reponseData.getData());
			
			if(appUser != null) {
				ShareWeightHelpUserLogEntity shareWeightHelpUserLog = shareWeightHelpUserLogMapper
						.selectOneByreduceWeightFundLogId(reduceWeightFundLogEntity.getUuId(), appUser.getUuId());
				if(shareWeightHelpUserLog != null)shareWeightDetailsData.setIsHelp(true);
				if(appUser.getUuId().equals(weightChangeLog.getUserId()))shareWeightDetailsData.setIsSelf(true);
			}
			
			
			baseDataResDto.setData(shareWeightDetailsData);
		}

		return baseDataResDto;
	}

	@Override
	public BaseDataResDto<List<ShareWeightUserHelpList>> getShareWeightUserHelpList(BaseDataReqDto<String> param) {
		logger.info("UserServiceImpl.getShareWeightUserHelpList ,param is {}", JSON.toJSONString(param));
		Integer startPage = (param.getMetaData().getPage() - 1)  * param.getMetaData().getSize();
		
		if(param.getMetaData() == null || startPage == null || param.getMetaData().getSize() == null) {
			return new BaseDataResDto<List<ShareWeightUserHelpList>>(
					Status.PARAMETERERROR);
		}
		
		List<ShareWeightHelpUserLogEntity> list = shareWeightHelpUserLogMapper
				.selectListByReduceWeightFundLogId(param.getData(),startPage, param.getMetaData().getSize());

		List<ShareWeightUserHelpList> shareWeightUserHelpList = new ArrayList<ShareWeightUserHelpList>();

		for (ShareWeightHelpUserLogEntity shareWeightHelpUserLogEntity : list) {
			ShareWeightUserHelpList shareWeightUserHelp = new ShareWeightUserHelpList();
			BeanUtils.copyProperties(shareWeightHelpUserLogEntity, shareWeightUserHelp);
			shareWeightUserHelp.setTime(shareWeightHelpUserLogEntity.getInTime());
			shareWeightUserHelpList.add(shareWeightUserHelp);
		}
		BaseDataResDto<List<ShareWeightUserHelpList>> baseDataResDto = new BaseDataResDto<List<ShareWeightUserHelpList>>(
				Status.SUCCESS);
		baseDataResDto.setData(shareWeightUserHelpList);
		return baseDataResDto;
	}

	@Override
	public BaseDataResDto<List<ReduceWeightFundLogResData>> getReduceWeightFundLogList(
			BaseDataReqDto<ReduceWeightFundLogReqData> param, String maijiToken) {
		logger.info("UserServiceImpl.getReduceWeightFundLogList ,param is {},maijiToken is {}",
				JSON.toJSONString(param), maijiToken);

		// 获得用户id
		AppUser appUser = appUserService.checkToken(maijiToken);

		if (appUser == null) {
			logger.info("UserServiceImpl.getReduceWeightFundLogList,appUser is {}", JSON.toJSONString(appUser));
			return new BaseDataResDto<List<ReduceWeightFundLogResData>>(Status.PARAMETERERROR, "token 无效 ");
		}
		
		List<ReduceWeightFundLogEntity> list =  reduceWeightFundLogMapper.getReduceWeightFundLogEntityListByTime(appUser.getUuId(), param.getData().getStartTime(),  param.getData().getEndTime());
		List<ReduceWeightFundLogResData>  listReduceWeightFundLogResData = new ArrayList<ReduceWeightFundLogResData>();
		for(ReduceWeightFundLogEntity reduceWeightFundLogEntity : list) {
			ReduceWeightFundLogResData reduceWeightFundLogResData = new ReduceWeightFundLogResData();
			BeanUtils.copyProperties(reduceWeightFundLogEntity, reduceWeightFundLogResData);
			
			Integer count = shareWeightHelpUserLogMapper.getSumCount(reduceWeightFundLogEntity.getUuId());
			reduceWeightFundLogResData.setCount(count);
			
			Double sumMoney = shareWeightHelpUserLogMapper.getSumFund(reduceWeightFundLogEntity.getUuId());
			
			Double baseMoney = 0.0;
			if(reduceWeightFundLogEntity.getIsBaseFund() == 1) {
				baseMoney = reduceWeightFundLogEntity.getMoney();
			}
			if (sumMoney != null) {
				sumMoney = Arith.add(2, baseMoney,sumMoney);
			} else {
				sumMoney = baseMoney;
			}
			reduceWeightFundLogResData.setMoney(sumMoney);
			
			listReduceWeightFundLogResData.add(reduceWeightFundLogResData);
		}
		
		BaseDataResDto<List<ReduceWeightFundLogResData>> response = new BaseDataResDto<List<ReduceWeightFundLogResData>>(Status.SUCCESS);
		response.setData(listReduceWeightFundLogResData);
		
		return response;
	}

    @Override
    public BaseDataResDto<ShareWeightHelpRule> findShareWeightHelpRule () {
        Query query = new Query(Criteria.where("type").is(CommonIntValueEnum.MONGO_RULE_TYPE_REDUCE_WEIGHT_HELP_FUND.getValue()));
        ShareWeightHelpRule shareWeightHelpRule = mongoTemplate.findOne(query, ShareWeightHelpRule.class, ShareOrderRule.TABLE_NAME);
        return new BaseDataResDto<ShareWeightHelpRule>(Status.SUCCESS).setData(shareWeightHelpRule);
    }

    @Override
    public BaseResDto updShareWeightHelpRule (ShareWeightHelpRule shareWeightHelpRule) {
        Query query = new Query(Criteria.where("type").is(CommonIntValueEnum.MONGO_RULE_TYPE_REDUCE_WEIGHT_HELP_FUND.getValue()));
        mongoTemplate.findAndRemove(query, ShareWeightHelpRule.class, ShareWeightHelpRule.TABLE_NAME);
        mongoTemplate.save(shareWeightHelpRule, ShareWeightHelpRule.TABLE_NAME);
        mongoTemplate.save(shareWeightHelpRule, ShareWeightHelpRule.TABLE_LOG_NAME);
        return new BaseResDto(Status.SUCCESS);
    }

    @Override
    public BaseDataResDto<List<ShareWeightHelpRule>> findAllShareWeightHelpRuleLogs(List<Date> updateDates) {
        Query query = new Query(Criteria.where("type").is(CommonIntValueEnum.MONGO_RULE_TYPE_REDUCE_WEIGHT_HELP_FUND.getValue()));
        query.skip(1).with(new Sort(new Sort.Order(Sort.Direction.DESC,"updateDate")));
        Date startDate = updateDates.size() > 0 ? updateDates.get(0): null;
        Criteria updateDateCriteria = Criteria.where("updateDate");
        Boolean updFlag = false;
        if (startDate != null) {
            updateDateCriteria = updateDateCriteria.gte(startDate);
            updFlag = true;
        }
        Date endDate = updateDates.size() > 1 ? updateDates.get(1): null;
        if (endDate != null) {
            updateDateCriteria = updateDateCriteria.lte(endDate);
            updFlag = true;
        }
        if (updFlag) query.addCriteria(updateDateCriteria);
        if (startDate == null && endDate == null) query.limit(1);
        List<ShareWeightHelpRule> shareWeightHelpRules = mongoTemplate.find(query, ShareWeightHelpRule.class, ShareWeightHelpRule.TABLE_LOG_NAME);
        return new BaseDataResDto<List<ShareWeightHelpRule>>(Status.SUCCESS).setData(shareWeightHelpRules);
    }

}
